﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;

using Skynet.BusinessEntities;
namespace Skynet.BusinessLogic.DataAccess
{
    public class CustomerRepository : MasterRepository<Customer>, ICustomerRepository
    {
        public CustomerRepository(IUnityContainer container)
            : base(container)
        { 

        }
        public override void Add(Customer item)
        {            
            var ctx = this.ContainerService.Resolve<SkyNetLibraryEntities>();            
            ctx.Customers.AddObject(item);
            ctx.SaveChanges();
            item.AcceptChanges();            
        }
        public override IEnumerable<Customer> GetAll()
        {
            var ctx = this.ContainerService.Resolve<SkyNetLibraryEntities>();
            var query = (from c in ctx.Customers select c);
            return query.ToList();
        }
        public override void Delete(Customer item)
        {
            var ctx = this.ContainerService.Resolve<SkyNetLibraryEntities>();
            var original = (from c in ctx.Customers where c.Id == item.Id select c).FirstOrDefault();
            if (original != null)
            {
                ctx.Customers.DeleteObject(original);
                ctx.SaveChanges();
            }
         
        }
        public override void Update(IEnumerable<Customer> items)
        {
            base.Update(items);
        }
        public override void Update(Customer item)
        {
            var ctx = this.ContainerService.Resolve<SkyNetLibraryEntities>();
            var original = (from c in ctx.Customers where c.Id == item.Id select c).FirstOrDefault();
            if (original == null) throw new System.Data.DeletedRowInaccessibleException("This record have been deleted by another user.");            
            ctx.Customers.ApplyCurrentValues(item);
            ctx.SaveChanges();
            
        }
        public override Customer GetOne(object key)
        {
            var ctx = this.ContainerService.Resolve<SkyNetLibraryEntities>();
            var query = (from c in ctx.Customers where c.Id == (Guid)key select c).SingleOrDefault();
            return query;
        }
        public Customer GetOneByUserName(string UserName)
        {
            var ctx = this.ContainerService.Resolve<SkyNetLibraryEntities>();
            var query = (from c in ctx.Customers where c.UserName == UserName select c).SingleOrDefault();
            return query; 
        }
    }
}
